

#include "lib.h"
#include "composite_key.h"

uint8_t composite_key_init(COMPOSITE_KEY_STRUCT* composite_key,
					uint8_t* composite_key_key_list, uint8_t composite_key_key_list_len)
{
	if((composite_key == 0)||
		(composite_key_key_list == 0)||(composite_key_key_list_len < 2)){
		return 0;
	}

	composite_key->key_list = composite_key_key_list;
	composite_key->key_list_len = composite_key_key_list_len;
	composite_key->counter = 0;

	return 1;
}

//uint8_t composite_key_struct_check_err(COMPOSITE_KEY_STRUCT* composite_key)
//{
//	return 1;
//}

uint8_t composite_key_press_handler(COMPOSITE_KEY_STRUCT* composite_key,
											BIT_MARK_STRUCT* pressing_key_mark)
{
	uint16_t i = 0;
	uint8_t count = 0;

	if((composite_key == 0)||
		(composite_key->key_list == 0)||(composite_key->key_list_len < 2)){
		return 0;
	}

	while(1){
		if(bit_mark_get(pressing_key_mark, i) == 1){
			if(__include_check(composite_key->key_list,
							composite_key->key_list_len, i) == 1){
				count++;
			}
			else{
				i = 0;
				break;
			}
		}
		if(i == pressing_key_mark->bit_mark_count){
			if(count == composite_key->key_list_len){
				i = 1;
			}
			else{
				i = 0;
			}
			break;
		}
		i++;
	}

	return (uint8_t)i;
}

uint8_t composite_key_press_handler_in_order(COMPOSITE_KEY_STRUCT* composite_key,
									BIT_MARK_STRUCT* pressing_key_mark,
									uint8_t press_key_num)
{
	uint16_t i = 0;
	uint8_t count = 0;

	if((composite_key == 0)||
		(composite_key->key_list == 0)||(composite_key->key_list_len < 2)){
		return 0;
	}

	while(1){
		if(bit_mark_get(pressing_key_mark, i) == 1){
			if(__include_check(composite_key->key_list,
							composite_key->key_list_len, i) == 1){
				count++;
			}
			else{
				i = 0;
				break;
			}
		}
		if(i == pressing_key_mark->bit_mark_count){
			break;
		}
		i++;
	}

	if(i == 0){
		composite_key->counter = 0;
		return 0;
	}

	if(((composite_key->key_list[composite_key->counter]) == press_key_num)
		&&(count-1 == composite_key->counter)){
		if(composite_key->counter == composite_key->key_list_len-1){
			composite_key->counter = 0;
			return 1;
		}
		composite_key->counter++;
		return 0;
	}
	else{
		composite_key->counter = 0;
		return 0;
	}
}


